package com.qdxwx.data.service.user;

import com.qdxwx.common.page.PageRequest;
import com.qdxwx.data.mapper.user.UserBuyMapper;
import com.qdxwx.models.enums.ModuleType;
import com.qdxwx.models.order.OrderDetail;
import com.qdxwx.models.user.UserBuy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 用户购买记录
 * Qdx NetSchool Platform
 * @author qdxwx
 * @updateTime 2022/5/25
 * @description
 */
@Service
public class UserBuyServiceImpl implements UserBuyService {

    @Autowired
    private UserBuyMapper userBuyMapper;

    @Override
    public int create(OrderDetail detail) {
        ModuleType moduleType = ModuleType.get(detail.getOrderType());
        if (moduleType == null) {
            return 0;
        }
        UserBuy userBuy = new UserBuy();
        userBuy.setUserId(detail.getUserId());
        userBuy.setUserName(detail.getUserName());
        userBuy.setModuleId(moduleType.ordinal());
        userBuy.setInfoId(detail.getCourseId());
        userBuy.setTitle(detail.getCourseName());
        userBuy.setPrice(detail.getPrice());
        userBuy.setExpireDate(detail.getAuthDate());
        return insert(userBuy);
    }

    @Override
    public UserBuy get(long id) {
        return userBuyMapper.get(id);
    }

    @Override
    public int insert(UserBuy userBuy) {
        if (!checkIsBuy(userBuy)) {
            if (userBuy.getExpireDate() == null) {
                userBuy.setExpireDate(LocalDate.now().plusDays(365));
            }
            userBuy.setCreateTime(LocalDateTime.now());
            return userBuyMapper.insert(userBuy);
        }
        return 0;
    }

    @Override
    public int delete(long id) {
        return userBuyMapper.delete(id);
    }

    @Override
    public int count(UserBuy userBuy) {
        return userBuyMapper.count(userBuy);
    }

    @Override
    public int countByCourseId(int courseId) {
        UserBuy query = new UserBuy();
        query.setInfoId(courseId);
        return userBuyMapper.count(query);
    }

    @Override
    public List<UserBuy> getList(UserBuy userBuy, PageRequest page) {
        return userBuyMapper.getList(userBuy, page);
    }

    @Override
    public boolean checkIsBuy(UserBuy userBuy) {
        return userBuyMapper.checkIsBuy(userBuy.getUserId(), userBuy.getModuleId(), userBuy.getInfoId()) != null;
    }

    @Override
    public boolean checkIsBuy(long userId, int moduleId, long infoId) {
        if (userId == 0 || moduleId == 0 || infoId == 0) {
            return false;
        }
        return userBuyMapper.checkIsBuy(userId, moduleId, infoId) != null;
    }

    @Override
    public int updateCombine(long userId1, long userId2) {
        if(userId1 < 1 || userId2 < 1){
            throw new RuntimeException("更新用户课程：参数错误");
        }
        return userBuyMapper.updateCombine(userId1,userId2);
    }
}
